#coding=utf-8

import time
import datetime
import urllib
import re
from Cookie import SimpleCookie
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import db

class Classifier(db.Model):
  cId = db.StringProperty(required=True)
  cTopic = db.StringProperty(required=True)
  cLang = db.StringProperty(required=True)
  cImgURL = db.StringProperty()
  cTag = db.ListProperty(str)
  cAuthor = db.ListProperty(str)
  cRating = db.RatingProperty()
  cModifyTime = db.DateTimeProperty(auto_now_add=True)

class Category(db.Model):
  catId = db.StringProperty(required=True)
  cId = db.StringProperty(required=True)
  catName = db.StringProperty(required=True)
  catFeature = db.ListProperty(str)
  catImgURL = db.StringProperty()
  classifier = db.ReferenceProperty(Classifier)

class VSM(db.Model):
  catId = db.StringProperty(required=True)
  cId = db.StringProperty(required=True)
  vector = db.ListProperty(str)
  cat = db.ReferenceProperty(Category)

class Profile(db.Model):
  id = db.StringProperty(required=True)
  guid = db.StringProperty(required=True)
  dfLang = db.StringProperty(required=True)


class About(webapp.RequestHandler):

  def get(self):
    self.response.out.write('Hello world!')


class QueryClassifier(webapp.RequestHandler):

  def get(self):
	cId = self.request.get('cId')
	query = self.request.get('q')
	if cId == "":
		greeting = ("<a href=\"/l\">back to home</a>.")
		self.response.out.write("<html><body>%s</body></html>" % greeting)
		exit
	
	if query == "":
		self.response.out.write("""<html><title></title><body>
<div>
<form action="/conf" method="get">
<input type=hidden name=cId value="""+cId+""">
<div><label class="in">query</label><input class="la" type=text name=q></div>
<div><label class="in"></label><input class="la" type=submit></div>
</form>
</div>
</body></html>""")
		exit


	self.response.out.write('Hello world!')

class ListClassifier(webapp.RequestHandler):

  def get(self):
    self.response.out.write('Hello world!')


class CreateCategory(webapp.RequestHandler):
  def get(self):
	self.request.charset='utf-8'
	cId = self.request.get('cId')
	# db
	clfrList = db.GqlQuery("SELECT * FROM Classifier WHERE cId = :1", cId)
	if clfrList.count() != 1:
		self.response.out.write('fail cId: '+cId)
		return
	for clfr in clfrList:
		topic = clfr.cTopic
		lang = clfr.cLang
		imgurl = clfr.cImgURL
		tag = clfr.cTag
		author = clfr.cAuthor

	# output
	tag_html=""
	for t in tag:
		tag_html += t + " "
	author_html=""
	for ar in author:
		author_html += ar + " "

	topic_html = ("""<div class="q"><img class="img" src="%s" height="100"></div><div class="q"><span class="la">%s</span> <br>%s - %s</div>""" % (imgurl,topic,author_html,tag_html))
	self.response.out.write("""<html><title>laqor - build your classifier</title><style type="text/css">.img {width:auto;} .q {display:block; float:left; } form div {display:block; clear:left; margin:5px 0 5px;} .in {display:block; float:left; width:70px; margin:0 0 5px; padding:3px 5px; text-align:right; border: 1px solid #FFFFFF;background: #FFFFFF;font-family: tahoma, helvetica, sans-serif;font-style: normal;font-size: 16px;color: #454743;} .la {font-family: tahoma, helvetica, sans-serif;font-style: bold;font-size: 20px;color: #82983e;} .left {float: left;} .gs-text-box,.gs-watermark,#searchcontrol {display:none;}</style><body>
<div>
<h1>Build a classifier</h1>
<div class="la">Step 2: Create categories</div>
<div>
  <div class="left">"""+topic_html+"""</div>
  <div class="left">
<form action="/cc" method="post">
<input type="hidden" name="cId" value='"""+cId+"""'>
<input id="imageurl" type="hidden" name="image">
<div><label class="in">Category</label><textarea class="la" name=category></textarea></div>
<div><label class="in">Feature</label><textarea class="la" name=feature></textarea> seperate by comma</div>
<div><label class="in">Image</label> <span id="saved_results" class="left"></span> <a class="goog" href="#">select</a></div>
<div><label class="in"> </label><input class="la" type="submit" value="Create Category"></div>
</form>
<div id="searchcontrol"></div> 
  </div>
</div>
</body>
<script type="text/javascript" src="/js/jquery.js"></script>
<script src="http://www.google.com/jsapi?key=ABQIAAAAgHV4OHfNdvOsg6vWVbj-4RRt1ye8wG_gu3iJw1dBKayQ_n49FBRE0zBhJ1JWC_s4CcNY1ha_1iSU-A" type="text/javascript"></script>
<script type="text/javascript">
google.load("search", "1");
  function OnLoad() {
    var searchControl = new google.search.SearchControl();
    var options = new google.search.SearcherOptions();
    options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
    searchControl.addSearcher(new google.search.ImageSearch(), options);
    searchControl.draw(document.getElementById("searchcontrol"));
    searchControl.setOnKeepCallback(this, MyKeepHandler);
    function MyKeepHandler(result) {
      var node = result.html.cloneNode(true);
      $("#saved_results > *").remove();
      var savedResults = document.getElementById("saved_results");
      savedResults.appendChild(node);
      $("#searchcontrol").toggle();
      document.getElementById("imageurl").value = $("a.gs-image").attr("href"); 
    }
  }
google.setOnLoadCallback(OnLoad);
$("a.goog").live("click", function(){$("#searchcontrol").toggle(); return false;});
</script>     
</html>""")
		


  def post(self):
	self.request.charset='utf-8'
	user = users.get_current_user()
	if not user:
		greeting = ("<a href=\"/\">back to home</a>.")
		self.response.out.write("<html><title>laqor - build your classifier</title><body>%s</body></html>" % greeting)
		return
	cId = self.request.get('cId')
	category = self.request.get('category')
	feature = self.request.get('feature')
	image = self.request.get('image')
    	self.response.out.write("%s %s %s %s" %(cId,category,feature,image))
	# db access
	# get classifier
	clfrList = db.GqlQuery("SELECT * FROM Classifier WHERE cId = :1", cId)
	if clfrList.count() != 1:
		self.response.out.write('fail cId: '+cId)
		return
	for clfr in clfrList:
		topic = clfr.cTopic
		lang = clfr.cLang
		break
	s = ("""
	# save category
	catId = datetime.datetime.today().strftime("%y%j%H%M%S")
	cat = Category(
			catId = str(catId),
			cId = str(cId),
			catName = category,
			catFeature = feature.split(","),
			catImgURL = image,
			classifier = clfr
			)
	cat.put()

	self.redirect("/cc?cId=%s" % str(cId) )
""")

	# get vsm
	feature_str = ""
	for f in feature.split(","):
		feature_str += f +" "
	q_raw = ("%s %s" % (topic,feature_str)) 
	q = urllib.quote(q_raw.encode('utf8'))
	url = ( "http://5hotword.appspot.com/q?q=%s&lr=%s&m=api" % (str(q) ,lang))
	# fetch 
	result = urlfetch.fetch(url)
	if not result.status_code == 200:
		self.response.out.write('fail')
	#self.response.out.write(result.content)
	ret = str(result.content).decode("utf8")
	#self.response.out.write(ret)
	jDecode = simplejson.JSONDecoder()
	x = jDecode.decode(ret)
	for t,tf in x.iteritems():
		#self.response.out.write(t +" "+ str(tf) +"<br>")





class Profiling(webapp.RequestHandler):
  def get(self):
	self.request.charset='utf8'
	user = users.get_current_user()
	if not user:
		greeting = ("<a href=\"/\">back to home</a>.")
		self.response.out.write("<html><title>laqor - build your classifier</title><body>%s</body></html>" % greeting)
		return

	# db
	profileList = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	if profileList.count() > 1:
		self.response.out.write( "system error: dup guid %s" % user.email())
		return

	# check register
	id=''
	dfLang=''
	for profile in profileList:
		id = profile.id
		dfLang = profile.dfLang

	if id == '':
		id_str = '<input class="la" type=text name=id>'
	else:
		id_str = ('<span class="la">%s</span>' % id)

	if dfLang == '':
		dfLang = 'lang_zh-TW';

	self.response.out.write("""<html><head><title>laqor - setting & preference</title><meta http-equiv="content-type" content="text/html; charset=UTF-8"><style type="text/css">form div {display:block; clear:left; margin:5px 0 5px;} .in {display:block; float:left; width:150px; margin:0 0 5px; padding:3px 5px; text-align:right; border: 1px solid #FFFFFF;background: #FFFFFF;font-family: tahoma, helvetica, sans-serif;font-style: normal;font-size: 20px;color: #454743;} .la {font-family: tahoma, helvetica, sans-serif;font-style: bold;font-size: 20px;color: #82983e;} .left {float: left;} .gs-text-box,.gs-watermark,#searchcontrol {display:none;}</style></head>
<body>
<div>
<div class="la">Setting</div>
<form action="/conf" method="post">
<div><label class="in">Id: </label> """+id_str+"""</div>
<div><label class="in">Language: </label> <select id="lang" name="dfLang" class="la"><option value="lang_zh-CN" >Chinese&nbsp;(Simplified)</option><option value="lang_zh-TW" >Chinese&nbsp;(Traditional)</option><option value="lang_en">English</option><option value="lang_ja" >Japanese</option><option value="lang_ko" >Korean</option></select> </div>
<div><label class="in"></label><input class="la" type="submit" value="Save"></div>
</form>
</div>
<div><a href="/">home</a></div>
</body>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
$("#lang").children().each(function(){
if ($(this).attr("value") == \""""+dfLang+"""\")
  $(this).attr("selected","true");
});
</script>
</html>""")
	# db
	#profileList2 = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	#for profile2 in profileList2:
	#	id = profile2.id
	#	dfLang = profile2.dfLang
	#debug 
 	#self.response.out.write(id + "<br>")
 	#self.response.out.write(dfLang + "<br>")
	#c = SimpleCookie()
	#self.encoding = "UTF-8"
	#c.load(self.request.cookies)
	#id = urllib.unquote(self.request.cookies["id"])
	#id_utf8 = id.decode('unicode-escape')
	#self.response.out.write(id_utf8 + "<br>")

  def post(self):
	self.request.charset='utf-8'
	user = users.get_current_user()
	if not user:
		greeting = ("<a href=\"/\">back to home</a>.")
		self.response.out.write("<html><title>laqor - build your classifier</title><body>%s</body></html>" % greeting)
		return

	# db
	profileList = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	if profileList.count() > 1:
		self.response.out.write( "system error: dup guid %s" % user.email())
		return

	id = self.request.get('id')
	dfLang = self.request.get('dfLang')
	if profileList.count() == 0:
		# insert
		if id == '':
			self.response.out.write( "input error: empty id" )
			return

		idList = db.GqlQuery("SELECT * FROM Profile WHERE id = :1", id)
		if idList.count() > 0:
			self.response.out.write( "input error: dup id %s" % id)
			return
		else:
			# create
			p = Profile(	id = id, 
					guid = user.email(),
					dfLang = dfLang
					)
			p.put()
	else:
		#update setting
		for profile in profileList:
			profile.dfLang = dfLang
			profile.put()

	# db
	profileList2 = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	for profile2 in profileList2:
		id = profile2.id
		dfLang = profile2.dfLang
 
 	#self.response.out.write( urllib.quote(id.encode('utf8')) + "<br>")
 	#self.response.out.write(dfLang)
	#return

	# cookie
	c = SimpleCookie()
	# save to cookie
	c["id"] = urllib.quote(id.encode('unicode-escape'))
	c["id"]["expires"]= str(time.time() + 60*60*24*365)
	c["id"]["path"]="/"
	header_value = c["id"].output(header='').lstrip()
	self.response.headers._headers.append(('Set-Cookie', header_value))
	c["dfLang"] = dfLang
	c["dfLang"]["expires"]= str(time.time() + 60*60*24*365)
	c["dfLang"]["path"]="/"
	header_value = c["dfLang"].output(header='').lstrip()
	self.response.headers._headers.append(('Set-Cookie', header_value))

	self.redirect("/conf")
	 

class CreateClassifier(webapp.RequestHandler):

  def editAll(self):
	self.response.out.write("""<html><title>laqor - build your classifier</title><style type="text/css">form div {display:block; clear:left; margin:5px 0 0;} .in {display:block; float:left; width:70px; margin:0 0 5px; padding:3px 5px; text-align:right; border: 1px solid #FFFFFF;background: #FFFFFF;font-family: tahoma, helvetica, sans-serif;font-style: normal;font-size: 14px;color: #454743;} .la {font-family: tahoma, helvetica, sans-serif;font-style: bold;font-size: 13px;color: #82983e;} .txt {display: none;}</style><body>
<div>
<form action="/conf" method="get">
<div><label class="in">Topic</label><textarea class="la" name=topic></textarea></div>
<div class="cat">
<div><label class="in">Category</label><textarea class="la" name=category></textarea> <a class="text" href="#">>></a> <textarea class="la txt" name=feature></textarea></div>
</div>
<div><label class="in"><a class="add" href="#">+</a></label><input class="la" type="button" value="Training"></div>
</form>
</div>
</body>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
$("a.add").click(function(){
  $("div.cat").append('<div><label class="in"> <a href="#" class="del">-</a> Category</label><textarea class="la" name=q></textarea> <a class="text" href="#">>></a> <textarea class="la txt"></textarea></div>');
});
$("a.text").live("click", function(){$(this).next().toggle(); return false;});
$("a.del").live("click", function(){$(this).parent().parent().remove(); return false;});
</script>     
</html>""")

  def post(self):
	self.request.charset='utf-8'
	user = users.get_current_user()
	if not user:
		greeting = ("<a href=\"%s\">Sign in or register</a>." % users.create_login_url("/"))
		self.response.out.write("<html><title>laqor - build your classifier</title><body><div>%s</div> <div><a href=\"/about\">about</a></div></body></html>" % greeting)
		return
	
	# db
	profileList = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	if profileList.count() != 1:
		greeting = ("<a href=\"/conf\">Register a laqor Id to build your classifier!</a>." )
		self.response.out.write("<html><title>laqor - build your classifier</title><body><div>%s</div> <div><a href=\"/about\">about</a></div></body></html>" % greeting)
		return

	for profile in profileList:
		id = profile.id
		dfLang = profile.dfLang

	topic = self.request.get('topic')
	tag = self.request.get('tag')
	image = self.request.get('image')
	#self.response.out.write('%s %s %s' % (topic ,tag ,image))

	# db access
	cId = datetime.datetime.today().strftime("%f%y%j%H%M%S")
	clfr = Classifier(
			cId = str(cId),
			cTopic = topic,
			cLang = dfLang,
			cImgURL = image,
			cTag = tag.split(','),
			cAuthor = [id] 
			)
	clfr.put()

	self.redirect("/cc?cId=%s" % str(cId) )

  def get(self):
	user = users.get_current_user()
	if not user:
		greeting = ("<a href=\"%s\">Sign in or register</a>." % users.create_login_url("/"))
		self.response.out.write("<html><title>laqor - build your classifier</title><body><div>%s</div> <div><a href=\"/about\">about</a></div></body></html>" % greeting)

		return

	# db
	profileList = db.GqlQuery("SELECT * FROM Profile WHERE guid = :1", user.email())
	if profileList.count() != 1:
		greeting = ("<a href=\"/conf\">Register a laqor Id to build your classifier!</a>." )
		self.response.out.write("<html><title>laqor - build your classifier</title><body><div>%s</div> <div><a href=\"/about\">about</a></div></body></html>" % greeting)
		return

	# output
	self.response.out.write("""<html><title>laqor - build your classifier</title><style type="text/css">form div {display:block; clear:left; margin:5px 0 5px;} .in {display:block; float:left; width:70px; margin:0 0 5px; padding:3px 5px; text-align:right; border: 1px solid #FFFFFF;background: #FFFFFF;font-family: tahoma, helvetica, sans-serif;font-style: normal;font-size: 20px;color: #454743;} .la {font-family: tahoma, helvetica, sans-serif;font-style: bold;font-size: 20px;color: #82983e;} .left {float: left;} .gs-text-box,.gs-watermark,#searchcontrol {display:none;}</style><body>
<div>
<h1>Build a classifier</h1>
<div class="la">Step 1: Create a topic</div>
<div>
<form action="/c" method="post">
<input id="imageurl" type="hidden" name="image">
<div><label class="in">Topic</label><textarea class="la" name=topic></textarea></div>
<div><label class="in">Tag</label><textarea class="la" name=tag></textarea> seperate by comma</div>
<div><label class="in">Image</label> <span id="saved_results" class="left"></span> <a class="goog" href="#">select</a></div>
<div><label class="in"> </label><input class="la" type="submit" value="Create Topic"></div>
</form>
</div>
<div id="searchcontrol"></div>
</div>
</body>
<script type="text/javascript" src="/js/jquery.js"></script>
<script src="http://www.google.com/jsapi?key=ABQIAAAAgHV4OHfNdvOsg6vWVbj-4RRt1ye8wG_gu3iJw1dBKayQ_n49FBRE0zBhJ1JWC_s4CcNY1ha_1iSU-A" type="text/javascript"></script>
<script type="text/javascript">
google.load("search", "1");
  function OnLoad() {
    var searchControl = new google.search.SearchControl();
    var options = new google.search.SearcherOptions();
    options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
    searchControl.addSearcher(new google.search.ImageSearch(), options);
    searchControl.draw(document.getElementById("searchcontrol"));
    searchControl.setOnKeepCallback(this, MyKeepHandler);
    function MyKeepHandler(result) {
      var node = result.html.cloneNode(true);
      $("#saved_results > *").remove();
      var savedResults = document.getElementById("saved_results");
      savedResults.appendChild(node);
      $("#searchcontrol").toggle();
      document.getElementById("imageurl").value = $("a.gs-image").attr("href"); 
    }
  }
google.setOnLoadCallback(OnLoad);
$("a.goog").live("click", function(){$("#searchcontrol").toggle(); return false;}); 
</script>     
</html>""")


class MainHandler(webapp.RequestHandler):

  def get(self):
	self.response.out.write("""<html><title>laqor - build your classifier</title><style type="text/css">form div {display:block; clear:left; margin:5px 0 5px;} .in {display:block; float:left; width:70px; margin:0 0 5px; padding:3px 5px; text-align:right; border: 1px solid #FFFFFF;background: #FFFFFF;font-family: tahoma, helvetica, sans-serif;font-style: normal;font-size: 20px;color: #454743;} .la {font-family: tahoma, helvetica, sans-serif;font-style: bold;font-size: 20px;color: #82983e;} .left {float: left;} .gs-text-box,.gs-watermark,#searchcontrol {display:none;}</style><body>
<div>
<h1>laqor - share your expertise to world</h1>
<div class="la">Play 1: Browse and play classifie <a href="/l">go</a></div>
<div class="la">Play 2: Build a classifier <a href="/c">go</a></div>
<div><a href="/about">About laqor</a></div>
</div>
</body>
<script type="text/javascript" src="/js/jquery.js"></script>
</html>""")



def main():
  application = webapp.WSGIApplication([('/', MainHandler),
	  				('/c',CreateClassifier),
	  				('/cc',CreateCategory),
	  				('/q',QueryClassifier),
	  				('/l',ListClassifier),
	  				('/conf',Profiling),
	  				('/about',About)],
                                       debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
